#include "exportmanager.h"

#include "../exporters/iexporter.h"

#include <fspersistencecommon.h>
#include <istorage.h>
#include <persistence.h>

#include <QtCore/QUrl>

using namespace core;
using namespace fspersistence;
using namespace swp;

ExportManager* exportManager = 0;

ExportManager* ExportManager::getInstance()
{
    if (exportManager == 0)
    {
        exportManager = new ExportManager();
    }

    return exportManager;
}

void ExportManager::destroy()
{
    delete exportManager;
    exportManager = 0;
}

void ExportManager::registerExporter(const core::MimeType& mimetype,
    IExporter* exporter)
{
    if (!m_registeredExporters.contains(mimetype))
    {
        m_registeredExporters[mimetype] = exporter->copy();
    }
}

void ExportManager::unregisterExporter(const core::MimeType& mimetype)
{
    if (m_registeredExporters.contains(mimetype))
    {
        IExporter* exporter = m_registeredExporters[mimetype];

        m_registeredExporters.remove(mimetype);
        delete exporter;
    }
}

void ExportManager::exportReport(
    const QSharedPointer<core::IDocument>& report)
{
    IStorage* storage = Persistence::getStorage(FILE_SYSTEM_STORAGE); // fs storage only

    Q_ASSERT(storage != 0); // can't happen

    if (m_registeredExporters.size() == 1)
    {
        bool canceled = false;

        const MimeType expMimetype =  m_registeredExporters.keys().first();

        QUrl url = storage->urlForSave(report->name(), expMimetype, canceled);

        if (!canceled)
        {
            m_registeredExporters[expMimetype]->exportReport(url, report);
        }
    }
    else
    {
        // TODO: show popup with choice
    }
}

ExportManager::ExportManager() : m_registeredExporters()
{

}

ExportManager::~ExportManager()
{

}
